import * as Router from 'koa-router'
import * as Joi from 'joi'
import * as userService from '../services/user.service'
import { badParams, stats } from '../stats'

const router = new Router({
  prefix: '/api/user'
})

// 注册 ok √
router.post('/register', async ctx => {
  const schema = Joi.object({
    username: Joi.string().required(),
    password: Joi.string().min(6).max(18).required()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  const result = await userService.register(value)
  ctx.body = {
    stat: 'OK',
    msg: '注册成功了呢',
    data: result
  }
})

// 登录 ok √
router.post('/login', async ctx => {
  const schema = Joi.object({
    username: Joi.string().min(2).max(10).required(),
    password: Joi.string().min(6).max(18).required()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  const user = await ctx.state.userInfo
  if (user) throw stats.ERR_REPEAT
  try {
    const { token, user } = await userService.login(value)
    ctx.set('Set-Cookie', `token=${token}; path=/; httpOnly`)
    ctx.body = {
      stat: 'OK',
      user
    }
  } catch (error) {
    ctx.body = error
  }
})

// 登出
router.post('/logout', async ctx => {
  const token = ctx.cookies.get('token')
  await userService.logout(token)
  ctx.set(
    'Set-Cookie',
    `token=; path=/; expires=${new Date().toUTCString()}; httpOnly`
  )
  ctx.body = {
    stat: 'OK'
  }
})

// 修改密码 ok
router.post('/update/pwd', async ctx => {
  const user = await ctx.state.userInfo
  const schema = Joi.object({
    oldpwd: Joi.string().min(6).max(18),
    newpwd: Joi.string().min(6).max(18)
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  await userService.updatepwd(user._id, value)
  ctx.body = {
    stat: 'OK',
    msg: '修改密码成功'
  }
})

// 当前用户详情信息
router.post('/info', async ctx => {
  const user = await ctx.state.userInfo
  if (user) {
    ctx.body = {
      stat: 'OK',
      user
    }
  } else throw stats.ERR_NOT_LOGIN
})

// 更新用户信息
router.post('/update/info', async ctx => {
  const user = await ctx.state.userInfo
  const schema = Joi.object({
    nickname: Joi.string().allow(''),
    signature: Joi.string().allow(''),
    qqnumber: Joi.string().allow(''),
    avatar: Joi.string().allow(''),
    gender: Joi.number(),
    major: Joi.array().items(Joi.string().required()).min(1).required()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  if (user) {
    await userService.updateinfo(user._id, value)
    ctx.body = {
      stat: 'OK',
      msg: '修改个人信息成功'
    }
  } else throw stats.ERR_NOT_LOGIN
})

// 获取用户详情
router.post('/other/info', async ctx => {
  const schema = Joi.object({
    userId: Joi.string().required()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  const token = ctx.cookies.get('token')
  if (token) {
    const user = await userService.userInfo(token)
    const data = await userService.otherUserInfo(value.userId, user._id)
    ctx.body = {
      stat: 'OK',
      user: data
    }
  } else {
    const data = await userService.otherUserInfo(value.userId)
    ctx.body = {
      stat: 'OK',
      user: data
    }
  }
})

// 关注/取消 用户
router.post('/add/focus', async ctx => {
  const schema = Joi.object({
    userId: Joi.string().required(),
    flag: Joi.boolean().required()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  const user = await ctx.state.userInfo
  if (user) {
    const msg = await userService.dealfocus(user._id, value.userId, value.flag)
    ctx.body = {
      stat: 'OK',
      msg
    }
  } else throw stats.ERR_NOT_LOGIN
})

// 获得动态列表 -> 可以只展示评论吗
router.post('/dynamic', async ctx => {
  const schema = Joi.object({
    userId: Joi.string().required(),
    skip: Joi.number().required(),
    limit: Joi.number().required(),
    type: Joi.number()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  const data = await userService.dylist(value)
  ctx.body = {
    stat: 'OK',
    data
  }
})

// 关注列表, 被关注列表
router.post('/focus', async ctx => {
  const schema = Joi.object({
    destId: Joi.string().required(),
    skip: Joi.number().required(),
    limit: Joi.number().required(),
    flag: Joi.boolean().required()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  const data = await userService.ulist(value)
  ctx.body = {
    stat: 'OK',
    data
  }
})

router.post('/cars', async ctx => {
  const token = ctx.cookies.get('token')
  if (token) {
    const user = await userService.userInfo(token)
    const data = await userService.cars(user._id)
    ctx.body = {
      stat: 'OK',
      msg: data
    }
  }
})

export default router
